package com.cloud.socket;

import jakarta.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * WebSocket服务端消息
 *
 * @author yzj
 */
public class WebSocketBuilder {

    private static Logger logger = LoggerFactory.getLogger(WebSocketBuilder.class);
    /**
     * 线程安全的无序的集合
     */
    public static CopyOnWriteArraySet<Session> SESSIONS = new CopyOnWriteArraySet<>();
    /**
     * 存储在线连接数
     */
    public static Map<String, Session> SESSION_POOL = new HashMap<>();

    /**
     * 此为广播消息
     *
     * @param data 消息
     */
    public static boolean sendAllMessage(Object data) {
        String message = String.valueOf(data);
        logger.info("[SocketServer消息]广播消息:" + message);
        for (Session session : SESSIONS) {
            try {
                if (session.isOpen()) {
                    session.getAsyncRemote().sendText(message);
                }
                return true;
            } catch (Exception e) {
                logger.error("[SocketServer消息]发送广播消息失败:" + e.getMessage());
            }
        }
        return false;
    }

    /**
     * 此为单点消息
     *
     * @param userId 用户编号
     * @param data   消息
     */
    public static boolean sendOneMessage(String userId, Object data) {
        String message = String.valueOf(data);
        logger.info("[SocketServer消息]单点消息:" + message);
        Session session = SESSION_POOL.get(userId);
        if (session != null && session.isOpen()) {
            try {
                synchronized (session) {
                    session.getAsyncRemote().sendText(message);
                }
                return true;
            } catch (Exception e) {
                logger.error("[SocketServer消息]发送单点消息失败:" + e.getMessage());
            }
        }
        return false;
    }

    /**
     * 此为单点消息/多人
     *
     * @param userIds 用户编号列表
     * @param data    消息
     */
    public static boolean sendMoreMessage(List<String> userIds, Object data) {
        String message = String.valueOf(data);
        logger.info("[SocketServer消息]批量消息:" + message);
        for (String userId : userIds) {
            Session session = SESSION_POOL.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    session.getAsyncRemote().sendText(message);
                    return true;
                } catch (Exception e) {
                    logger.error("[SocketServer消息]发送批量消息失败:" + e.getMessage());
                }
            }
        }
        return false;
    }

}
